// @ts-check
const { execSync } = require('child_process');
const fs = require('node:fs');
const readline = require('readline');

const GITEE_TOKEN = process.env.GITEE_TOKEN ?? '';
const GITEE_OWNER = process.env.GITEE_OWNER ?? '';

if (!GITEE_TOKEN) {
  console.log('GITEE_TOKEN not found');
  process.exit(1);
}

if(!GITEE_OWNER){
  console.log('GITEE_OWNER not found');
  process.exit(1);
}

console.log(`GITEE_TOKEN is ${GITEE_TOKEN}`);

// 文件夹名称
const EXPECTED_EXECUTION_DIRECTORY_NAME = 'rn-permission';
// 三方库名称
const REPO_NAME = 'rn-permissions';
// 远程仓库地址
const GITEE_URL = 'https://gitee.com/your_username/react-native-permissions';
// 模块名
const MODULE_NAME = 'permissions';
// har包的导出地址
const HAR_FILE_OUTPUT_PATH = `tester/harmony/${MODULE_NAME}/build/default/outputs/default/${MODULE_NAME}.har`;
// 发npm的组织名-包名
const UNSCOPED_NPM_PACKAGE_NAME = '@react-native-oh-tpl/react-native-permissions';

const GITEE_REPOS = 'react-native-oh-library';
const TARGET_BRANCH = 'master';
// pr描述信息
const RELEASE_BODY = ''; // release的pr可以不绑定信息，目前暂时留白
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

function runDeployment() {
  if (!process.cwd().endsWith(EXPECTED_EXECUTION_DIRECTORY_NAME)) {
    console.log(
      `This script should be executed from ${EXPECTED_EXECUTION_DIRECTORY_NAME} directory`
    );
    process.exit(1);
  }
  if (!isRepositoryClean()) {
    console.log(
      'Repository should be clean, on main branch and up to date with upstream.'
    );
    process.exit(1);
  }

  let version = '';
  const currentVersion = JSON.parse(
    fs.readFileSync('./package.json').toString()
  )['version'];

  console.log(`current version ${currentVersion}`);

  rl.question(
    `Current version: ${currentVersion}. Enter new version: `, 
    (newVersion) => {
      version = newVersion;
      console.log(`new version:${version}`);
    //   execSync(`npm run update_version  -- --new-version ${version}`, {
    //     stdio: 'inherit',
    //   });

      rl.question(
        `Please generate ${HAR_FILE_OUTPUT_PATH} file. Once you finish type 'done': `, 
        (answer) => {
        //   harPackageMove(answer);

          rl.question(
            'Are changes good to be release? (yes/no): ', 
            (answer) => {
              if (answer.toLowerCase() === 'yes') {
                CommitAndPush(version);
              } else {
                console.log('Deployment aborted.');
                rl.close();
              }
            }
          );
        }
      );
    }
  );
}

function isRepositoryClean() {
    //   const status = execSync('git status --porcelain', { encoding: 'utf-8' });
      const status = false;
      const branch = execSync('git branch --show-current', {
        encoding: 'utf-8',
      }).trim();
      const isUpdated =
        execSync('git rev-list HEAD...origin/master --count', {
          encoding: 'utf-8',
        }).trim() === '0';
      return !status && branch === 'master' && isUpdated;
    }

function harPackageMove(answer) {
  if (answer !== 'done') {
    console.log('Deployment aborted');
    process.exit(1);
  }
  console.log(
    `Copying ${`../${HAR_FILE_OUTPUT_PATH}`} to ./harmony dir`
  );
  if (!fs.existsSync(`../${HAR_FILE_OUTPUT_PATH}`)) {
    console.log(`Couldn't find ${HAR_FILE_OUTPUT_PATH}.`);
    process.exit(1);
  }
}

async function CommitAndPush(version) {
  execSync(
    `git checkout -b release-${REPO_NAME}-${version}`
  );
  execSync('git add -A');
  execSync(
    `git commit -m "release: ${REPO_NAME}@${version}"`,
    {
      stdio: 'inherit',
    }
  );
  execSync(`git push -u origin HEAD --no-verify`, {
    stdio: 'inherit',
  });
  execSync(`git tag v${version}`);
  execSync(`git push -u origin v${version} --no-verify`, {
    stdio: 'inherit',
  });
  const mergeRequestId = await createMergeRequest(
    `release-${REPO_NAME}-${version}`,
    `release: ${REPO_NAME}@${version}`
  );
  console.log(`Please merge the following Merge Request:\n
https://gitee.com/${GITEE_OWNER}/${REPO_NAME}/pulls/${mergeRequestId}`);
  rl.close();
}

async function createMergeRequest(sourceBranch, title) {
  try {
    const response = await fetch(
      `https://gitee.com/api/v5/repos/${GITEE_OWNER}/${REPO_NAME}/pulls`,
      {
        method: 'POST',
        headers: {
          'Authorization': `token ${GITEE_TOKEN}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          title: title,
          head: `${GITEE_OWNER}:${sourceBranch}`, // 确保这里的 GITEE_OWNER 是实际的用户名
          base: `${TARGET_BRANCH}`,
          body: `${RELEASE_BODY}`,
          prune_source_branch: true, // 合并后删除源分支
        }),
      }
    );
    if (!response.ok) {
      const errorMessage = await response.text();
      throw new Error(`Failed to create pull request: ${response.statusText} - ${response.status} - ${errorMessage}`);
    }
    const responseData = await response.json();
    return responseData.number; // 获取pr对应id号
  } catch (error) {
    console.error('Error happens when create pull request:', error);
    throw error;
  }
}

runDeployment();